<!-- <template>
  <div class="div1" v-if="userInfo">
    <el-upload drag :action="uploadUrlWithUserID" multiple :before-upload="beforeUpload">
      <el-icon class="el-icon--upload"><i-ep-UploadFilled /></el-icon>
      <div class="el-upload__text">
        拖拽文件 or <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          上传限制大小2G
        </div>
      </template>
    </el-upload>
  </div>
  <el-empty v-else description="这里空空如也">
  </el-empty>
</template>

<script setup lang="ts">
import { useStore } from 'vuex';

const store = useStore();
const userInfo = computed(() => store.state.user);

// 假设的基础上传URL  
const baseUploadUrl = '/api/file/upload';

const uploadUrlWithUserID = computed(() => `${baseUploadUrl}?userID=${userInfo.value.email}`);

const beforeUpload = (file: File) => {
  const isLt2G = file.size / 1024 / 1024 < 2048;
  if (!isLt2G) {
    alert('大小不能超过 2GB!');
    return false;
  }
  return true;
};  
</script>


<style scoped>
.div1 {
  margin-top: 50px;
}
</style> -->


<template>
  <div class="upload-container">
    <el-upload
      v-if="userInfo"
      drag
      :show-file-list="false"
      :before-upload="handleBeforeUpload"
    >
      <el-icon class="el-icon--upload"><i-ep-UploadFilled /></el-icon>
      <div class="el-upload__text">拖拽文件 or <em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">上传限制大小2G，支持断点续传</div>
      </template>
    </el-upload>
    <el-empty v-else description="请先登录"></el-empty>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import axios from 'axios';
import { useUserStore } from '@/stores/userStore'; // 引入 Pinia store
import { ElMessage } from 'element-plus';

const userStore = useUserStore(); // 使用 Pinia store
const userInfo = computed(() => userStore.user);

// 假设的基础上传URL
const baseUploadUrl = '/api/file/upload';

// 存储上传进度、文件信息、分块数量和当前分块序号
const uploadProgress = ref<number>(0);
const uploadingFile = ref<File | null>(null);
const chunkCount = ref<number>(0);
const currentChunkIndex = ref<number>(0);

// 计算带有用户ID的上传URL
const uploadUrlWithUserID = computed(() => {
  if (userInfo.value) {
    return `${baseUploadUrl}?userID=${userInfo.value.email}`;
  }
  return '';
});

// 处理文件上传前的逻辑
const handleBeforeUpload = (file: File) => {
  // 存储文件并初始化上传进度
  uploadingFile.value = file;
  uploadProgress.value = 0;

  // 初始化分块数量和当前分块序号
  initializeChunkedUpload(file);

  // 开始上传文件
  startChunkedUpload();

  // 阻止默认上传行为
  return false;
};

// 初始化分块上传的相关信息
const initializeChunkedUpload = (file: File) => {
  const chunkSize = 5 * 1024 * 1024; // 5MB per chunk
  chunkCount.value = Math.ceil(file.size / chunkSize);
  currentChunkIndex.value = 0;
};

// 分块上传文件
const startChunkedUpload = async () => {
  if (!uploadingFile.value) return;

  const chunkSize = 5 * 1024 * 1024; // 5MB per chunk
  const totalSize = uploadingFile.value.size;
  let uploadedSize = 0;

  while (currentChunkIndex.value < chunkCount.value) {
    const start = currentChunkIndex.value * chunkSize;
    const end = Math.min(start + chunkSize, totalSize);
    const chunk = uploadingFile.value.slice(start, end);

    const formData = new FormData();
    formData.append('fileName', uploadingFile.value.name);
    formData.append('chunkNumber', currentChunkIndex.value.toString());
    formData.append('totalChunks', chunkCount.value.toString());

    formData.append('chunk', chunk);

    formData.append('start', start.toString());
    formData.append('totalSize', totalSize.toString());

    try {
      const response = await axios.post(uploadUrlWithUserID.value, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: (progressEvent) => {
          // 更新当前分块的上传进度
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          const chunkProgress = percentCompleted / 100;
          const overallProgress = (currentChunkIndex.value / chunkCount.value) + (chunkProgress / chunkCount.value);
          uploadProgress.value = Math.round(overallProgress * 100);
        },
      });

      if (response.status === 200 && response.data.code !== -1) {
        // 假设服务器正确处理了分块上传
        uploadedSize += chunkSize;
        currentChunkIndex.value++;
      } else {
        ElMessage.error(response.data.msg);
        break;
      }
    } catch (error) {
      ElMessage.error('上传过程中发生错误');
      console.error(error);
      break;
    }
  }

  if (currentChunkIndex.value === chunkCount.value) {
    ElMessage.success('文件上传成功');
  }
};
</script>
 
<style scoped>
.upload-container {
  margin-top: 50px;
}
</style>